package com.itheima;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class test {
    //jDBC数据源方式为摸板填充数据
    @Test
    public void test1() throws Exception {
        //创建与数据库的连接
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/health", "root", "root");

        //jrxml摸板路径
        String jrxmlPath = "E:\\IdeaProjects\\chizhou_healthy\\JasperReports\\src\\main\\resources\\Demo1.jrxml";
        //设置根据jrxl摸板生成的jasper文件的目录
        String jsaperPath = "E:\\IdeaProjects\\chizhou_healthy\\JasperReports\\src\\main\\resources\\Demo1.jasper";
        //编译摸板
        JasperCompileManager.compileReportToFile(jrxmlPath,jsaperPath);
        //为模板准备数据
            //页脚的公司名
        Map map = new HashMap();
        map.put("company","传智播客");

        //因为摸板文件中定义了sql语句，所以只要给jasper提供一个数据库连接就可以自动添加数据
        JasperPrint jasperPrint = JasperFillManager.fillReport(jsaperPath, map, connection);
        //输出PDF文件
        String PDFpath="D:\\Test.pdf";
        JasperExportManager.exportReportToPdfFile(jasperPrint,PDFpath);
    }
    //javabean方式为摸板填充数据
    @Test
    public void test2() throws Exception{
        //jrxml摸板路径
        String jrxmlPath = "E:\\IdeaProjects\\chizhou_healthy\\JasperReports\\src\\main\\resources\\Demo2.jrxml";
        //设置根据jrxl摸板生成的jasper文件的目录
        String jsaperPath = "E:\\IdeaProjects\\chizhou_healthy\\JasperReports\\src\\main\\resources\\Demo2.jasper";
        //编译摸板
        JasperCompileManager.compileReportToFile(jrxmlPath,jsaperPath);
        //为模板准备数据
        //页脚的公司名
        Map map = new HashMap();
        map.put("company","传智播客");

        //为表单准备数据
        List<Map> list = new ArrayList();
        Map map1 = new HashMap();
        map1.put("name","入职体检套餐");
        map1.put("code","RZTJ");
        map1.put("age","18-60");
        map1.put("sex","女");
        Map map2 = new HashMap();
        map2.put("name","阳光爸妈老年健康体检");
        map2.put("code","YGBM");
        map2.put("age","55-60");
        map2.put("sex","女");
        list.add(map1);
        list.add(map2);
        //以javabean作为数据源，来填充数据
        JasperPrint jasperPrint = JasperFillManager.fillReport(jsaperPath, map,new JRBeanCollectionDataSource(list));
        //输出PDF文件
        String PDFpath="D:\\Test.pdf";
        JasperExportManager.exportReportToPdfFile(jasperPrint,PDFpath);
    }
}
